//搜索页面
//author：王梦阳

// 搜索商品功能实现：点击搜索，向后台发送请求，后台发送搜索到的商品并把数据返回给前端，当返回的数据
// 不为空时跳转到展示商品页面

var userId = localStorage.getItem("user"); //用户id

//通过关键字搜索
document.getElementById('btn_Search').addEventListener('tap', function() {
	let keyWord = document.getElementById("search").value;
	let itemId = "";
	let htmlContentS = "";
	console.log(keyWord);
	//点击搜索后清空输入框内容
	htmlContentS+=
	`<input type="search" id="search" class="mui-input-clear" placeholder="搜索商品">`;
	$(".mui-search").html(htmlContentS);
	//通过关键字搜索
	$.ajax({
		type: "GET",
		url: "http://39.98.158.247:8040/item/find",
		data: {
			name: keyWord
		},
		success: function(data) {
			console.log(data);
			//获取搜索到的商品并挂载到页面
			if (data.data.length != 0) {
				console.log(data);
				let htmlContent = ``;
				for (var i = 0; i < data.data.length; i++) {
					console.log(data.data[0].item_img);
					htmlContent +=
						`<div class="item"id="${i}" >
						<img  class="item-image" src="${data.data[i].item_img}"/>
						<div class="item-content">
						<span class="item-title">${data.data[i].item_name}</span>
						<span class="item-shop">${data.data[i].item_brand}</span>
						<span class="item-price">￥${data.data[i].item_price}</span>
						<span class="item-sale">已售 ${data.data[i].item_sales} 件</span>
						</div>
					</div>`

				}
				$("#item-list").html(htmlContent);

				for (var i = 0; i < data.data.length; i++) {
					// 实现点击搜索到的商品跳转到商品详情页,同时记录一次商品浏览
					document.getElementById(i).addEventListener('tap', function() {
						itemId = data.data[this.id].item_id;
						console.log(itemId);
						$.ajax({
							type: "POST",
							dataType: "json",
							async: false,
							contentType: "application/json",
							url: "http://39.98.158.247:8040/browse/insert?userId=" + userId + "&itemId=" + itemId,
							success: function() {
								console.log("insert success");
							},
							error: function() {
								console.log("request error");
							}
						})
						
						window.open("search-item.html", "_blank");
						localStorage.status = 0;
						// localStorage.dataset = JSON.stringify(data);
						localStorage.id = itemId;
					});
				}
			} else {
				mui.alert("未搜索到指定商品");
			}
		},
		error: function() {
			console.log("request error");
		}
	});

});


//选择图片
function getHeadImage() {
	if (mui.os.plus) {
		var buttonTit = [{
			title: "拍照"
		}, {
			title: "从手机相册选择"
		}];
		plus.nativeUI.actionSheet({
			title: "上传图片",
			cancel: "取消",
			buttons: buttonTit
		}, function(b) { /*actionSheet 按钮点击事件*/
			switch (b.index) {
				case 0:
					break;
				case 1:
					getImage(); /*拍照*/
					break;
				case 2:
					galleryImg(); /*打开相册*/
					break;
				default:
					break;
			}
		})
	}
}

// 拍照获取图片  
function getImage() {
	var c = plus.camera.getCamera();
	c.captureImage(function(e) {
		plus.io.resolveLocalFileSystemURL(e, function(entry) {
			var imgSrc = entry.toLocalURL() + "?version=" + new Date().getTime(); //拿到图片路径 
			getBase64(imgSrc, 500, 500)
				.then(function(base64) {
					uploadImg(base64);
				}, function(err) {
					console.log(err);
				});

		}, function(e) {
			console.log("读取拍照文件错误：" + e.message);
		});
	}, function(s) {
		console.log("erroraaa" + s.message);
	}, {
		filename: "_doc/camera/"
	})
}

// 从相册中选择图片   
function galleryImg() {
	// 从相册中选择图片  
	plus.gallery.pick(function(e) {
		for (var i in e.files) {
			var fileSrc = e.files[i];
			getBase64(fileSrc)
				.then(function(base64) {
					uploadImg(base64);
				}, function(err) {
					console.log(err);
				});
		}
	}, function(e) {
		if (e.code == 8) { //没有权限 
			var btnArray = ["确定"];
			mui.confirm('请在【设置】-【项目名称】中打开相机及相册权限！', '相册权限未开', btnArray, function(e) {
				if (e.index == 1) {} else {}
			})
		}
		console.log("取消选择图片");
	}, {
		filter: "image",
		multiple: true,
		maximum: 1,
		system: false,
		onmaxed: function() {
			onAlert('最多只能选择1张图片');
		}
	});
}

//传入图片路径，返回base64
function getBase64(img) {
	function getBase64Image(img, width, height) { //width、height调用时传入具体像素值，控制大小 ,不传则默认图像大小
		var canvas = document.createElement("canvas");
		var size = getSizeAction.GetSize(img.width, img.height)
		if (size == -1) {
			mui.toast("图片不合格，请重新上传");

		} else {
			//mui.toast(size);
			canvas.width = img.width * size; //按照照片的0.1比例压缩
			canvas.height = img.height * size; //按照照片的0.1比例压缩
			var ctx = canvas.getContext("2d");
			ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
			var dataURL = canvas.toDataURL();
			return dataURL;
		}
	}
	var image = new Image();
	image.crossOrigin = '';
	image.src = img;
	var deferred = $.Deferred();
	if (img) {
		image.onload = function() {
			deferred.resolve(getBase64Image(image)); //将base64传给done上传处理
		}
		return deferred.promise(); //问题要让onload完成后再return sessionStorage['imgTest']
	}
}

//上传图片搜索商品
function uploadImg(img) {
	$.ajax({
		type: "POST",
		url: "http://39.98.158.247:8040/item/img/search",
		dataType: "json",
		data: {
			"img": img,
		},
		success: function(data) {
			console.log(data);
			console.log(data.data[0].item_id);
			if (data.data.length != 0) {
				console.log(JSON.stringify(data));
				let htmlContent = ``;
				console.log(data.data.length);
				for (var i = 0; i < data.data.length; i++) {
					if(data.data[i]==null){
						continue;
					}					
					htmlContent +=
						`<div class="item"id="${i}" >
						<img  class="item-image" src="${data.data[i].item_img}"/>
						<div class="item-content">
						<span class="item-title">${data.data[i].item_name}</span>
						<span class="item-shop">${data.data[i].item_brand}</span>
						<span class="item-price">￥${data.data[i].item_price}</span>
						<span class="item-sale">已售 ${data.data[i].item_sales} 件</span>
						</div>
					</div>`
				}
				$("#item-list").html(htmlContent);

				for (var i = 0; i < data.data.length; i++) {
					// 实现点击搜索到的商品跳转到商品详情页并记录一次商品浏览
					document.getElementById(i).addEventListener('tap', function() {
						itemId = data.data[this.id].item_id;
						console.log(itemId);
						$.ajax({
							type: "POST",
							dataType: "json",
							async: false,
							contentType: "application/json",
							url: "http://http://39.98.158.247:8040/browse/insert?userId=" + userId + "&itemId=" + itemId,
							success: function() {
								console.log("insert success");
							},
							error: function() {
								console.log("request error");
							}
						})
						window.open("search-item.html", "_blank");
						localStorage.status = 0;
						// localStorage.dataset = JSON.stringify(data);
						localStorage.id = itemId;
					});
				}
			} else {
				mui.alert("未搜索到指定商品");
			}
		},
		error: function() {
			console.log("request error");
		}
	})
}
